package com.lenovo.leos.filebrowser.netdisk;


import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.ServiceConnection;
import android.os.IBinder;
import android.util.Log;


public class FileSyncServiceManager {
	
	public static String TAG = "FileSyncServiceManager";
	private Context mContext;
	private static FileSyncServiceManager mInstance;
	private FileSyncService fileSyncService;
	
	private FileSyncServiceManager(Context context){
		this.mContext = context;
	}
	
	public static FileSyncServiceManager getInstance(Context context){
		if(null == mInstance){
			mInstance = new FileSyncServiceManager(context);
		}
		
		return mInstance;
	}
	
	private ServiceConnection serviceConnection = new ServiceConnection() {
		public void onServiceConnected(ComponentName name, IBinder binder) {
			Log.i(TAG, "==> onServiceConnected");

			fileSyncService = ((FileSyncService.LocalBinder) binder).getService();
			log("onServiceConnected,fileSyncService == null " + (null == fileSyncService));
		}

		public void onServiceDisconnected(ComponentName name) {
			Log.i(TAG, "==> onServiceDisconnected");
			fileSyncService = null;
		}
	};
	
	
	
	public FileSyncService doBindService(){
		mContext.bindService(new Intent(mContext, 
				FileSyncService.class), serviceConnection, Context.BIND_AUTO_CREATE);
		
//		while(null == fileSyncService){
//			try {
//				Thread.sleep(1000);
//				Log.d(TAG,"############################# waiting for bind the FileSyncService");
//			} catch (InterruptedException e) {
//				e.printStackTrace();
//			}
//		}
		return fileSyncService;
	}
	
	public void unBindService(){
		mContext.unbindService(serviceConnection);
	}
	
//	public FileSyncService getFileSyncService(){
//		//在下载，上传过程中，有时候总会显示fileSyncService 为空
//		if(null != fileSyncService){
//			return fileSyncService;
//		}else{
//			//this may cause the program shutdown
//			throw new IllegalStateException("the fileSyncService isn't instante correctyly");
//		}
//	}
	
	public static  void log(String msg){
		for(int i=0;i<10;i++){
			Log.d("FileSyncService","########################## msg is: " + msg);
		}
	}

}
